<template>
	<view>
		<!-- 懒加载动画 -->
		<view class="loading-box">
			<u-loading :show="loadingone" color="#41ADBA" size="70"></u-loading>
		</view>
		<view v-show="!loadingone" :style="'bottom:'+KeyboardHeight+'px;'">
			<navbar name="发布帖子"></navbar>
			<view class="borderbtm">
				<input type="text" class="inputclass" name="titleValue" v-model="titleValue" @input="titleV"
					placeholder="请输入标题" :focus="true" @blur="leaveInput" />
			</view>
			<view class="editor-wrapper">
				<editor name="editor2" type="text" id="editor" :show-img-resize="true" :show-img-toolbar="true"
					class="ql-container" placeholder="请输入正文" @statuschange="onStatusChange" :read-only="readOnly"
					@input="editorInput" @ready="onEditorReady" @blur="leaveInputHtml">
				</editor>
				<!-- <editor name="editor2" id="editor" class="ql-container" placeholder="请输入正文" :show-confirm-bar="true"
					@input="editorInput" @blur="leaveInput" @focus="testFocus">
				</editor> -->
			</view>
			<view class="accomplish-popup" v-show="addBean">
				完成任务 <image class="jkdimage"
					src="http://static.bsyjk.cn/fitness/37914A67E286429B99EF67FDE1D3F192.png" mode="健康豆"></image>
				+{{bean}}
			</view>

		</view>
		<view class="shareBtn-view">
			<view style="padding-left: 30upx;" @tap="insertImage(9,['album'])">
				<uni-icons color="#000" :size="24" type="image" />
			</view>
			<view style="padding-left: 30upx;" @tap="insertImage(1,['camera'])">
				<uni-icons color="#000" :size="24" type="camera" />
			</view>
			<view class="post-view">
				<button :disabled="disabled" @tap="formtTap" class="BeganToPlan">发帖</button>
			</view>
		</view>
	</view>
</template>
<script>
import uLoading from "@/uview-ui/components/u-loading/u-loading.vue"

	export default {
		components: {
			uLoading,
		},
		data() {
			return {
				uploadMap:false,
				release: true,
				forumId: '',
				auditStatus: 1,
				isSendShow: true,
				keyBoardHeight: 0, //距离底部距离
				disabled: false, //按钮禁用
				upPage: '', //上一个页面
				loadingone: false,
				addBean: false,
				strings: '',
				titleValue: '',
				readOnly: false,
				formats: {},
				html: '',
				bean: '',
				task: '',
				taskStepId: '', //任务id
			}
		},
		onLoad(e) {
			console.log(e, '6444444444444')
			if (e.givePoint) {
				this.bean = e.givePoint; //豆
			}
			this.upPage = e.page ? e.page : ''
			this.task = e.task;
			if (e.stepId) { //任务id
				this.taskStepId = e.stepId;
			}
			let postAmessage = uni.getStorageSync('postAmessage');
			console.log(postAmessage,'777777')
			if (e.forumId) { //草稿箱value
				this.html = postAmessage.html;
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context
					this.editorCtx.setContents({
						html: postAmessage.html //e.html为赋值内容。
					})
				}).exec()
			}
			if (e.forumId) { //草稿箱title
				this.titleValue = postAmessage.titleValue
			}
			if (e.forumId) { //主键id
				this.forumId = e.forumId
			}
		},
		onShow() {
			// this.auditStatus = 1;
		},
		onHide() {
			// console.log('onHide')
			// this.auditStatus = 0;
			// if (this.html.length >= 10 &&!this.uploadMap|| this.titleValue.length >= 5&&!this.uploadMap) {
			// 	this.auditStatus = 0;
			// 	this.formtTap() //调用保存草稿
			// }
		},
		onUnload() {
			let _this = this;
			if (this.html.length >= 1 && this.release && this.forumId == '' || this.titleValue.length >= 1 && this
				.release && this.forumId == '') {
				uni.showModal({
					title: '提示',
					content: '是否保存为草稿箱？',
					success: function(res) {
						if (res.confirm) {
							_this.auditStatus = 0;
							_this.formtTap() //调用保存草稿
							console.log('用户点击确定');
						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
					}
				});
			}
		},
		methods: {
			// html失去焦点
			leaveInputHtml() {
				if (this.html.length < 9) {
					uni.showToast({
						title: '内容不得少于10个字',
						icon: 'none',
						duration: 2000
					});
				}
			},
			//输入框失去焦点
			leaveInput() {
				if (this.titleValue.length < 4) {
					uni.showToast({
						title: '标题不得少于5个字',
						icon: 'none',
						duration: 2000
					});
				}
			},
			formtTap() {
				let title = this.titleValue,
					content = this.html;
				this.forum(title, content)
			},
			// 我的任务健康豆
			userPointRecord(taskStepId) { //我的页面
				let fdata = {
					userId: uni.getStorageSync(global.IS_DEV?'USER_DATA_BSY_T':'USER_DATA_BSY_Z').userId,
					pointDict: taskStepId,
				}
				let _this = this;
				this.$shopnew.post(global.apiUrls.userPointRecord, fdata)
					.then(res => {
						if (res.data.code == 1000) {
							_this.addBean = true //显示添加健康豆
							setTimeout(() => {
								_this.addBean = false //显示添加健康豆
							}, 1500);
						} else {
							uni.showToast({
								title: res.data.message,
								icon: "none",
								duration: 2000
							});
						}
					}).catch(err => {})
			},
			// 计划健康豆
			userTaskStep(taskStepId) {
				let _this = this;
				let fdata = {
					userId: uni.getStorageSync(global.IS_DEV?'USER_DATA_BSY_T':'USER_DATA_BSY_Z').userId,
					userStepId: taskStepId,
					taskAppendix: ''
				}
				this.$api.put(global.apiUrls.userTaskStep, fdata)
					.then(res => {
						if (res.data.code == 1000) {
							_this.addBean = true //显示添加健康豆
							setTimeout(() => {
								_this.addBean = false //显示添加健康豆
							}, 1500);
						} else {
							uni.showToast({
								title: res.data.message,
								icon: "none",
								duration: 2000
							});
						}
					}).catch(err => {})
			},
			forum(forumTitle, forumContent) {
				if (this.auditStatus === 0 || this.forumId != '' || this.html.length > 9 && this.titleValue.length > 4) {
					let _this = this,
						fdata = {
							forumContent: forumContent,
							forumTitle: forumTitle,
							userId: uni.getStorageSync(global.IS_DEV?'USER_DATA_BSY_T':'USER_DATA_BSY_Z').userId
						}
					fdata.auditStatus = this.auditStatus
					_this.disabled = true;
					if (this.forumId != '') {
						fdata.forumId = this.forumId;
						// cms
						_this.$cms.put(global.apiUrls.forum, fdata).then(res => {
							_this.disabled = false;
							if (res.data.code == 1000) {
								uni.showToast({
									title: res.data.message,
									duration: 2000
								});
								if (_this.task == 0 && _this.upPage == 'healthBeans') {
									_this.userPointRecord(_this.taskStepId)
								}else{
									_this.userTaskStep(_this.taskStepId)
								}
								_this.release = false; //不保存草稿箱
								setTimeout(() => {
									uni.navigateBack({
										delta: 1
									});
									uni.$emit('getUserForumListRefresh', '')
								}, 2000);
							} else {
								uni.showToast({
									title: res.data.message,
									icon: "none",
									duration: 2000
								});
							}
						}).catch(err => {})
					} else {
						// cms
						_this.$cms.post(global.apiUrls.forum, fdata).then(res => {
							_this.disabled = false;
							if (res.data.code == 1000) {
								uni.showToast({
									title: res.data.message,
									duration: 2000
								});
								if (_this.task == 0 && _this.upPage == '') { //来自首页
									_this.userTaskStep(_this.taskStepId)
								} else if (_this.task == 0 && _this.upPage == 'healthBeans') {
									_this.userPointRecord(_this.taskStepId)
								}
								_this.release = false; //不保存草稿箱
								setTimeout(() => {
									uni.navigateBack({
										delta: 1
									});
								}, 2000);
							} else {
								uni.showToast({
									title: res.data.message,
									icon: "none",
									duration: 2000
								});
							}
						}).catch(err => {})
					}

				} else if (this.titleValue.length < 4) {
					uni.showToast({
						title: '标题不得少于5个字',
						icon: 'none',
						duration: 2000
					});
				} else if (this.html.length < 9) {
					uni.showToast({
						title: '内容不得少于10个字',
						icon: 'none',
						duration: 2000
					});
				}
			},
			titleV(e) {
				// console.log(e)
				this.titleValue = e.detail.value
			},
			editorInput(e) {
				this.html = e.target.html
			},
			onStatusChange(e) {
				const formats = e.detail
				this.formats = formats
			},
			onEditorReady() {
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context
				}).exec()
			},
			insertImage(count, sourceType) {
				this.uploadMap = true;
				let t = this;
				uni.chooseImage({
					count: count,
					sourceType: sourceType,
					success: (res) => {
						console.log(res.tempFilePaths, '18000000000000000000')
						var imageSrc = res.tempFilePaths,
						upimageArr = [];

						for (let i = 0; i < imageSrc.length; i++) {
							upimageArr.push('')
							uni.showLoading({
							    title: '图片处理中'
							});
							let loginKey = global.IS_DEV?'USER_TOKEN_BSY_T':'USER_TOKEN_BSY_Z'

							uni.uploadFile({
								url: global.host+'cms-service/file',
								filePath: imageSrc[i],
								fileType: 'image',
								name: 'upfile',
								header: {
									'Authorization': uni.getStorageSync(loginKey),
									userSource: 1, //用户类型 1:C端用户  2:员工
								},
								success: (resdata) => {
									console.log(imageSrc,'32333333333')
									if(i == imageSrc.length-1){
										for(let j = 0;j<imageSrc.length;j++){
											t.editorCtx.insertImage({
												src: JSON.parse(resdata.data).result.url,
												alt: '图像',
												success: function() {
													console.log('insert image success')
													t.uploadMap = false;
												}
											})
										}
									}else{
										upimageArr[i] = JSON.parse(resdata.data).result.url;
									}
									// t.editorCtx.insertImage({
									// 	src: JSON.parse(resdata.data).result.url,
									// 	alt: '图像',
									// 	success: function() {
									// 		console.log('insert image success')
									// 		t.uploadMap = false;
									// 	}
									// })
									console.log('uploadImage success, res is:', )
									uni.hideLoading();
								},
								fail: (err) => {

									// if(i == imageSrc.length-1){
									// 	for(let j = 0;j<imageSrc.length;j++){
									// 		t.editorCtx.insertImage({
									// 			src: imageSrc[j],
									// 			alt: '图像',
									// 			success: function() {
									// 				console.log('insert image success')
									// 				t.uploadMap = false;
									// 			}
									// 		})
									// 	}
									// }
									uni.hideLoading();
									uni.showToast({
										title: '上传失败请稍后重试',
										icon: 'none',
										duration: 2000
									});
									// console.log('uploadImage fail', err);
								}
							});
						}


					}
				})
			}
		}
	}
</script>

<style lang="scss">
	/deep/.ql-editor.ql-blank:before {
		font-style: normal;
	}

	.borderbtm {
		width: 710upx;
		border-bottom: 1px dashed #979797;
		margin: 0 auto;
	}

	.editor-wrapper {
		width: 710upx;
		margin: 0 auto;
	}

	.insertImage {
		width: 41px;
		height: 34px;
		background: #000000;
	}

	.inputclass {
		height: 122upx;
		font-size: 44upx;
		font-weight: 500;
		color: #9B9B9B;
		line-height: 122upx;
		padding-left: 26upx;
	}

	.ql-container {
		font-size: 36upx;
		font-weight: 500;
		color: #9B9B9B;
		line-height: 50upx;
		padding: 32upx 0;
		min-height: 43vh;
	}


	.accomplish-popup {
		display: inline-block;
		width: 345upx;
		height: 90upx;
		background: #3A3A3A;
		border-radius: 15upx;
		opacity: 0.9;
		position: fixed;
		top: 50vh;
		left: 50%;
		transform: translateX(-50%);
		color: #fff;
		font-size: 28upx;
		font-weight: 500;
		color: #FFFFFF;
		line-height: 90upx;
		letter-spacing: 1px;
		text-align: center;

		.jkdimage {
			width: 44upx;
			height: 36upx;
		}
	}

	.shareBtn-view {
		width: 750upx;
		height: 100upx;
		display: flex;
		background: #F5F5F5;
		border-top: 1upx solid #979797;
		padding-top: 25upx;
	}

	.post-view {
		width: 200upx;
		padding-left: 400upx;

		.BeganToPlan {
			width: 154upx;
			height: 50upx;
			background: rgba(46, 167, 224, 1);
			line-height: 50upx;
			font-size: 24upx;
			color: #fff;
		}

	}
</style>
